package com.crl.ui.controls.pages
{
	import com.crl.ui.controls.events.TabEvent;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	
	public class TabNavigator extends Sprite
	{
		
		private var _selectItem:ITabItem;
		public var _tabList:Array;
		
		public function TabNavigator()
		{
			_tabList=new Array();
		}
		
		
		public function addTabItem(tabItem:ITabItem):void{
			tabItem.index=_tabList.length;
			if(tabItem.target){
				tabItem.target.visible=false;
			}
			tabItem.addEventListener(MouseEvent.CLICK,clickHander);
			
			_tabList.push(tabItem);
		}
		
		/**
		 * 删除一个tab项; 
		 * @param tabItem
		 * 
		 */		
		public function removeTabItem(tabItem:ITabItem):Boolean{
			var index:int=_tabList.indexOf(tabItem);
			
			if(index==-1)return false;
			
			tabItem.removeEventListener(MouseEvent.CLICK,clickHander);
			if(tabItem==this._selectItem){
				this.selectTabPage(tabItem.index);
			}
			
			_tabList.splice(index,1);
			
			return true;
		}
		
		/**
		 *清除所有的tab项; 
		 * 
		 */		
		public function clear():void{
			for each(var item:ITabItem in _tabList){
				item.removeEventListener(MouseEvent.CLICK,clickHander);
			}
			_selectItem.selected=false;
			var target:DisplayObject=_selectItem.target;
			if(target){
				target.visible=false;
			}
			
			_tabList.splice(0);
		}
		
		public function clickHander(event:MouseEvent):void{
			selectTabPage((event.currentTarget as ITabItem).index)
		}
		
		public function selectTabPage(index:int):void{
			var target:DisplayObject;
			if(_selectItem){
				target=_selectItem.target;
				if(target){
					target.visible=false;
				}
				_selectItem.selected=false;
				_selectItem.addEventListener(MouseEvent.CLICK,clickHander);
			}
			_selectItem=_tabList[index];
			if(_selectItem){
				target=_selectItem.target;
				if(target){
					target.visible=true;
				}
				_selectItem.selected=true;
				_selectItem.removeEventListener(MouseEvent.CLICK,clickHander);
			}
			
			this.dispatchEvent(new TabEvent(TabEvent.CHANGE,_selectItem));
		}
		
		
		public function getTabeItem(index:int):ITabItem{
			index=Math.max(0,Math.min(index,_tabList.length-1));
			return _tabList[index] as ITabItem;
			
		}
		
		/**
		 * 当前选择Tab项;
		 * @return 
		 * 
		 */		
		public function get selectItem():ITabItem{
			return this._selectItem;
		}
		
	}
}